// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

const {ccclass, property} = cc._decorator;
const POS=cc.Enum({
    TOP:300,
    BOTTOM:-500
})

@ccclass
export default class Main extends cc.Component {

    @property(cc.Prefab)
    public hamburger:cc.Prefab=null;
    @property(cc.Node)
    public hamburgerManger:cc.Node=null;
    @property({type:cc.AudioClip})
    public bgm:cc.AudioClip=null;

    public nowHamburger:cc.Node=null;

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {}

    start () {
        cc.audioEngine.playMusic(this.bgm,true);
        this.nowHamburger=this.newHamburger();
    }

    private newHamburger():cc.Node{
        this.node.on(cc.Node.EventType.TOUCH_END,this.downHamburger,this);
        let ham:cc.Node=cc.instantiate(this.hamburger);
        ham.parent=this.hamburgerManger;
        ham.x=0;
        ham.y=POS.TOP;
        // let act:cc.Action=cc.repeatForever(
        //     cc.sequence(
        //         cc.moveTo(-100,-100),
        //         cc.moveTo(100,100)
        //     )
        // );
        let act:cc.Action=cc.repeatForever(
            cc.sequence(
                cc.scaleTo(1,0),
                cc.scaleTo(1,1)
            )
        );
        ham.runAction(act);
        return ham;
    }
    private downHamburger():void{
        this.node.off(cc.Node.EventType.TOUCH_END,this.downHamburger,this);
        this.nowHamburger.stopAllActions();
        // 当页面中只有一个汉堡到位时，继续
        if(this.hamburgerManger.childrenCount===1){
            this.nowHamburger.runAction(cc.moveTo(0.5,0,POS.BOTTOM));
            this.scheduleOnce(()=>{
                this.nowHamburger=this.newHamburger();
            },1);
        }else{
            // 找到下方汉堡，两个相较，判断是否失败
            let index=this.hamburgerManger.childrenCount-2;
            let bottomNode=this.hamburgerManger.children[index];
            let posY=bottomNode.y+bottomNode.height+bottomNode.scaleY-bottomNode.scaleY*200;
            this.nowHamburger.runAction(cc.moveTo(0.5,0,posY));
            if(this.nowHamburger.scaleX>bottomNode.scaleX){
                alert('you are lose');
            }else{
                // 叠五个汉堡则游戏成功
                if(this.hamburgerManger.childrenCount===5){
                    alert('you are win!!!');
                    return;
                }
                this.scheduleOnce(()=>{
                    this.nowHamburger=this.newHamburger();
                },1);
            }
        }
    }
    // update (dt) {}
}